package com.umxwe.kill.seckill.config;

import com.alibaba.fastjson.JSONObject;
import com.umxwe.kill.core.domain.Result;
import com.umxwe.kill.core.domain.ResultCode;
import feign.FeignException;
import feign.Logger;
import feign.Response;
import feign.Util;
import feign.codec.DecodeException;
import feign.codec.Decoder;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import tk.mybatis.mapper.util.Assert;

import java.io.IOException;
import java.lang.reflect.Type;

@Configuration
public class FeignConfiguration implements Decoder {

    @Bean
    Logger.Level feignLoggerLevel(){
        return Logger.Level.FULL;
    }


    @Override
    public Object decode(Response response, Type type) throws IOException, DecodeException, FeignException {
        if (response.body() == null) {
            throw new DecodeException(response.status(), "没有返回有效的数据", response.request());
        }
        String bodyStr = Util.toString(response.body().asReader(Util.UTF_8));
        //对结果进行转换
            Result<T> result = JSONObject.parseObject(response.body().toString(),Result.class);
        Assert.isTrue(result.getCode() == ResultCode.SUCCESS,result.getMessage());
        return JSONObject.toJSON(result.getData()).toString();
    }
}
